import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:async';
import 'package:myapp/Common/UserAPI/UserAPIResponsitory.dart';
import 'package:myapp/Common/Remote/remote.dart';
import 'dart:io';
import 'dart:convert';
import 'package:meta/meta.dart';


class RemoteResponsitory {

//  static const REMOTE_POLLING_PATH = "https://bmwgatewayserviceint.chinacloudsites.cn/api/gateway/brs/webapi/v1/user/vehicles/LBV6P410XLMB49511/serviceExecutionStatus?eventId=c6567962-41bb-4d2b-afed-f51d9ee44668&serviceType=LIGHT_FLASH ";
//  static const REMOTE_EXECUTE_PATH = "https://bmwgatewayserviceint.chinacloudsites.cn/api/gateway/brs/webapi/v1/user/vehicles/LBV6P410XLMB49511/serviceExecutionStatus?eventId=c6567962-41bb-4d2b-afed-f51d9ee44668&serviceType=LIGHT_FLASH ";

  static const REMOTE_POLLING_PATH = "/api/gateway/brs/webapi/v1/user/vehicles/{vin}/serviceExecutionStatus?eventId={evenId}&serviceType={serviceType}";
  static const REMOTE_EXECUTE_PATH = "/api/gateway/brs/webapi/v1/user/vehicles/{vin}/executeService";


  final UserAPIResponsitory userAPIResponsitory;

  RemoteResponsitory({this.userAPIResponsitory});

  bool _isPolling = false;
  Timer _pollingTimer;
  DateTime _pollingStart;
  http.Client client = http.Client();

  Future<RemoteExecuteResult> execute(String vin, String service) async {
    var path = REMOTE_EXECUTE_PATH.replaceAll("{vin}", vin).replaceAll("{serviceType}", service);
    var fullAddressUrl = userAPIResponsitory.constructServerAddress(path);
    try{
      final response = await client.post(fullAddressUrl, headers: userAPIResponsitory.getHeaders(), body: {"serviceType": service});
      if (response.statusCode >= 200 || response.statusCode <400) {
        print("test1");
        return RemoteExecuteResult.fromJson(json.decoder.convert(response.body));
      } else {
        print("test2");
        return RemoteExecuteResult.fromJson({});
      }
    }catch (error) {
      print("test3");
      return RemoteExecuteResult.fromJson({});
    }
  }

  Stream<RemoteExecuteResult> polling(String vin, String service) async* {


    yield RemoteExecuteResult.fromJson({"": ""});
  }

  Stream<RemoteExecuteResult> _polling(String vin, String service) async* {

    final client = HttpClient();
    var path = REMOTE_EXECUTE_PATH.replaceAll("{vin}", vin).replaceAll("{serviceType}", service);


    yield RemoteExecuteResult.fromJson({"": ""});
  }




}